package com.quanquan.store.service;

import DTO.image.ImageDTO;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.quanquan.store.configBean.RabbitSender;
import com.quanquan.store.dao.CouponCacheDao;
import com.quanquan.store.dao.OrderCacheDao;
import com.quanquan.store.dto.AllOrderDTO;
import com.quanquan.store.dto.IdDTO;
import com.quanquan.store.dto.OrderDTO;
import com.quanquan.store.dto.UserDTO;
import com.quanquan.store.entity.*;
import com.quanquan.store.repository.*;
import com.quanquan.store.request.CouponRequest;
import com.quanquan.store.request.OrderRequest;
import com.quanquan.store.request.UserRequestBody;
import commond.IntegralOutPut;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import utils.DateUtils;
import utils.RandomUtil;
import utils.Request;
import utils.UUIDGenerator;

import java.util.*;

/**
 * @ClassName:OrderService
 * @Description:TODO
 * @Author:xiongjunbao
 * @Date:2019/3/21 16:57
 * @Version 1.0
 */
@Service
public class OrderService {


    private final OrderRepository orderRepository;
    private final CouponRepository couponRepository;
    private final CouponCodeRepository couponCodeRepository;
    private final RabbitSender rabbitSender;
    private final RestTemplate restTemplate;
    private final StoreCouponRepository storeCouponRepository;
    private final SquareRepository squareRepository;
    private final CouponService couponService;
    private final ShopMallRepository shopMallRepository;
    private final OrderCacheDao orderCacheDao;
    private final CouponCacheDao couponCacheDao;
    @Value("${module-url.userUrl}")
    private String userUrl;
    @Autowired
    public OrderService(OrderRepository orderRepository, CouponRepository couponRepository, CouponCodeRepository couponCodeRepository, RestTemplate restTemplate, RabbitSender rabbitSender, StoreCouponRepository storeCouponRepository, SquareRepository squareRepository, CouponService couponService, ShopMallRepository shopMallRepository, OrderCacheDao orderCacheDao, CouponCacheDao couponCacheDao) {
        this.orderRepository = orderRepository;
        this.couponRepository = couponRepository;
        this.couponCodeRepository = couponCodeRepository;
        this.rabbitSender = rabbitSender;
        this.restTemplate = restTemplate;
        this.storeCouponRepository = storeCouponRepository;
        this.squareRepository = squareRepository;
        this.couponService = couponService;
        this.shopMallRepository = shopMallRepository;
        this.orderCacheDao = orderCacheDao;
        this.couponCacheDao = couponCacheDao;
    }


    /**
     * 生成订单
     *
     * @param request
     * @return
     */
    public OrderDTO saveOrder(OrderRequest request) {
        OrderDTO orderDTO = new OrderDTO();
        Date date = new Date();
        String senderName = "系统";
        ShopMall shopMall = shopMallRepository.findByStatusRemoveAndId(request.getShopMallId());
        Coupon coupon = couponRepository.findByCouponId(shopMall.getCouponId());
        if (coupon == null) {
            orderDTO.setMsg("没有对应商品");
            return orderDTO;
        }
        if (request.getUserIntegral() < (coupon.getIntegral() * request.getCount())) {
            orderDTO.setMsg("用户积分不足");
            return orderDTO;
        }
        if (date.before(DateUtils.stringToDate(shopMall.getBuyTimeStart(), DateUtils.TIMESTAMP)) || date.after(DateUtils.stringToDate(shopMall.getBuyTimeEnd(), DateUtils.TIMESTAMP))) {
            orderDTO.setMsg("未到购买时间");
            return orderDTO;
        }
        Square square = squareRepository.findByStatus();
        if (square != null) {
            //判断用户是否超出商城限制购买的笔数  TODO
            List<Order> orderList = orderRepository.queryByUserIdPerDay(request.getUserId(), DateUtils.dateToString(date, DateUtils.DATE));
            if (square.getCount() != null && square.getCount() > 0) {
                if (orderList.size() >= square.getCount()) {
                    orderDTO.setMsg("超出商城当天兑换数量限制");
                    return orderDTO;
                }
            }
        }
        //判断用户当天购买的该券数量是否超出限制  TODO
        List<CouponCode> userCoupon = couponCodeRepository.queryByUserIdAndShopMallId(request.getUserId(), shopMall.getId(), DateUtils.dateToString(date, DateUtils.DATE));
        if (shopMall.getCount() != null && shopMall.getCount() > 0) {
            if (request.getCount() > shopMall.getCount() || request.getCount() + userCoupon.size() > shopMall.getCount()) {
                orderDTO.setMsg("超出卡券当天兑换数量限制");
                return orderDTO;
            }
        }
        //判断用户在优惠券可购买期间购买的该券数量是否超出限制  TODO
        List<CouponCode> buyCoupons = couponCodeRepository.queryByUserIdAndCouponIdAndBetween(request.getUserId(), shopMall.getId(), shopMall.getBuyTimeStart(), shopMall.getBuyTimeEnd());
        if (shopMall.getBuyTimeCount() != null && shopMall.getBuyTimeCount() > 0) {
            if (request.getCount() > shopMall.getBuyTimeCount() || request.getCount() + buyCoupons.size() > shopMall.getBuyTimeCount()) {
                orderDTO.setMsg("超出有效期内兑换数量限制");
                return orderDTO;
            }
        }
        //用户购买不限量券
        String useEnd = null;
        if (coupon.getUseTimeType() == 1) {
            useEnd = coupon.getUseTimeEnd();
        }
        if (coupon.getUseTimeType() == 2) {
            useEnd = DateUtils.dateToString(DateUtils.getDateAfterHour(coupon.getUseTimeHour()), DateUtils.TIMESTAMP);
        }
        if (coupon.getUseTimeType() == 3) {
            useEnd = DateUtils.dateToString(DateUtils.getEndOfDay(date), DateUtils.TIMESTAMP);
        }
        Order order = new Order();
        order.setId(UUIDGenerator.getUUID());
        order.setOrderNum(UUIDGenerator.getOrderIdByTime());
        order.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        order.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        order.setCouponId(shopMall.getCouponId());
        order.setUserId(request.getUserId());
        order.setCount(request.getCount());
        order.setStatusShow(0);
        order.setStatusRemove(0);
        order.setStoreId(request.getStoreId());
        //如果是积分支付
        if (coupon.getValueType() == 1) {
            //如果券是不限量的券，直接给用户创建一张被购买的券
            if (coupon.getSumType() == 1) {
                for (int i = 0; i < request.getCount(); i++) {
                    CouponCode couponCode = new CouponCode();
                    couponCode.setId(UUIDGenerator.getUUID());
                    couponCode.setCouponCode(UUIDGenerator.getOrderIdByTime());
                    couponCode.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    couponCode.setAddTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    couponCode.setCouponId(coupon.getId());
                    couponCode.setUserId(request.getUserId());
                    couponCode.setStatus(0);
                    couponCode.setType(coupon.getType());
                    couponCode.setUseTimeEnd(useEnd);
                    couponCode.setCouponName(coupon.getName());
                    couponCode.setUseTimeStart(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    couponCode.setSenderName(senderName);
                    couponCode.setShopMallId(shopMall.getId());
                    couponCodeRepository.saveAndFlush(couponCode);
                }
            } else {
                if (shopMall.getRemainTotal() >= request.getCount()) {
                    couponRepository.updateRemainTotal(shopMall.getId(), request.getCount());
                    //根据优惠券使用期限和券id查找对应的code，并将code锁定
                    List<CouponCode> couponCodeList = couponCodeRepository.queryByCouponIdAndStatus(coupon.getId());
                    if (couponCodeList.size() > 0) {
                        for (int i = 0; i < request.getCount(); i++) {
                            CouponCode couponCode = couponCodeList.get(i);
//                            couponCodeRepository.addUserCouponCode(couponCode.getId(), request.getUserId(), DateUtils.dateToString(date, DateUtils.TIMESTAMP), senderName, useEnd, shopMall.getId());
                        }
                    }
                } else {
                    orderDTO.setMsg("商品数量不足");
                    return orderDTO;
                }
            }
            //支付积分
            order.setIntegral(shopMall.getIntegral() * request.getCount());
            order.setPrice(0.0);
            //设置订单状态为已支付
            order.setStatus(1);
            orderRepository.saveAndFlush(order);
            //订单放入队列接受处理
            solveOrder(order, coupon, request.getStoreId());
        } else {
            //如果券是不限量的券，直接给用户创建一张被购买的券
            if (coupon.getSumType() == 1) {
                for (int i = 0; i < request.getCount(); i++) {
                    CouponCode couponCode = new CouponCode();
                    couponCode.setId(UUIDGenerator.getUUID());
                    couponCode.setCouponCode(UUIDGenerator.getOrderIdByTime());
                    couponCode.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    couponCode.setAddTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    couponCode.setCouponId(coupon.getId());
                    couponCode.setUserId(request.getUserId());
                    couponCode.setStatus(-1);
                    couponCode.setType(coupon.getType());
                    couponCode.setUseTimeEnd(useEnd);
                    couponCode.setCouponName(coupon.getName());
                    couponCode.setUseTimeStart(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    couponCode.setSenderName(senderName);
                    couponCode.setShopMallId(shopMall.getId());
                    couponCodeRepository.saveAndFlush(couponCode);
                }
            } else {
                if (shopMall.getRemainTotal() >= request.getCount()) {
                    couponRepository.updateRemainTotal(request.getCouponId(), request.getCount());
                    //根据优惠券使用期限和券id查找对应的code，并将code锁定
                    List<CouponCode> couponCodeList = couponCodeRepository.queryByCouponIdAndStatus(coupon.getId());
                    if (couponCodeList.size() > 0) {
                        for (int i = 0; i < request.getCount(); i++) {
                            CouponCode couponCode = couponCodeList.get(i);
                            couponCodeRepository.addUserCouponCodeAndStatus(couponCode.getId(), request.getUserId(), DateUtils.dateToString(date, DateUtils.TIMESTAMP), senderName, useEnd, shopMall.getId());
                        }
                    }
                } else {
                    orderDTO.setMsg("商品数量不足");
                    return orderDTO;
                }
            }
            //支付积分
            order.setIntegral(shopMall.getIntegral() * request.getCount());
            //如果是金额支付
            order.setPrice(Double.parseDouble(shopMall.getPrice()) * request.getCount());
            //设置订单状态为未支付
            order.setStatus(0);
            orderRepository.saveAndFlush(order);
        }
        BeanUtils.copyProperties(order, orderDTO);
        String type = coupon.getType().toString();
        orderDTO.setType(type);
        return orderDTO;
    }

    /**
     * 生成订单
     *
     * @param request
     * @return
     */
    public OrderDTO saveOrder1(OrderRequest request) {
        OrderDTO orderDTO = new OrderDTO();
        Date date = new Date();
        String senderName = "系统";
        Coupon coupon = couponRepository.findByCouponId(request.getCouponId());
        if (coupon == null) {
            orderDTO.setMsg("没有对应商品");
            return orderDTO;
        }
        if (date.before(DateUtils.stringToDate(coupon.getBuyTimeStart(), DateUtils.TIMESTAMP)) || date.after(DateUtils.stringToDate(coupon.getBuyTimeEnd(), DateUtils.TIMESTAMP))) {
            orderDTO.setMsg("未到购买时间");
            return orderDTO;
        }
      /*  if("7813166f674343feb60fde3720e283f8".equals(request.getCouponId())){
            List<CouponCode> couponCodeList = couponCodeRepository.queryByCouponIdAndStatus("b4f9848bad5e483dabee4476085b2c90",request.getUserId());
            if (couponCodeList.size() > 0) {
                return "已兑换了beauty up单色美甲券";
            }
        }
        if("b4f9848bad5e483dabee4476085b2c90".equals(request.getCouponId())){
            List<CouponCode> couponCodeList = couponCodeRepository.queryByCouponIdAndStatus("7813166f674343feb60fde3720e283f8",request.getUserId());
            if (couponCodeList.size() > 0) {
                return "已兑换了欧卡奴单色美甲券";
            }
        }*/
        Square square = squareRepository.findByStatus();
        if (square != null && square.getStatus() == 0) {
            // List<CouponCode> userCoupon1 = couponCodeRepository.queryByUserId(request.getUserId(), DateUtils.dateToString(date, DateUtils.DATE));

            //判断用户是否超出商城限制购买的笔数  TODO
            List<Order> orderList = orderRepository.queryByUserIdPerDay(request.getUserId(), DateUtils.dateToString(date, DateUtils.DATE));
            if (square.getCount() != null && square.getCount() > 0) {
                if (orderList.size() >= square.getCount()) {
                    orderDTO.setMsg("超出商城当天兑换数量限制");
                    return orderDTO;
                }
               /* if (request.getCount() > square.getCount() || request.getCount() + userCoupon1.size() > square.getCount()) {
                    return "超出商城当天兑换数量限制";
                }*/
               /* if (square.getCount() <= userCoupon1.size()) {
                    return "已达到当天商城兑换数量限制";
                }*/
            }
        }
        //判断用户当天购买的该券数量是否超出限制  TODO
        List<CouponCode> userCoupon = couponCodeRepository.queryByUserIdAndCouponId(request.getUserId(), request.getCouponId(), DateUtils.dateToString(date, DateUtils.DATE));
        if (coupon.getCount() != null && coupon.getCount() > 0) {
            if (request.getCount() > coupon.getCount() || request.getCount() + userCoupon.size() > coupon.getCount()) {
                orderDTO.setMsg("超出卡券当天兑换数量限制");
                return orderDTO;
            }
           /* if (coupon.getCount() <= userCoupon.size()) {
                return "已达到卡券当天兑换数量限制";
            }*/
        }
        //判断用户在优惠券可购买期间购买的该券数量是否超出限制  TODO
        List<CouponCode> buyCoupons = couponCodeRepository.queryByUserIdAndCouponId(request.getUserId(), request.getCouponId());
        if (coupon.getBuyTimeCount() != null && coupon.getBuyTimeCount() > 0) {
            if (request.getCount() > coupon.getBuyTimeCount() || request.getCount() + buyCoupons.size() > coupon.getBuyTimeCount()) {
                orderDTO.setMsg("超出有效期内兑换数量限制");
                return orderDTO;
            }
           /* if (coupon.getCount() <= userCoupon.size()) {
                return "已达到卡券当天兑换数量限制";
            }*/
        }

        //用户购买不限量券
        String useEnd = null;
        if (coupon.getUseTimeType() == 1) {
            useEnd = coupon.getUseTimeEnd();
        }
        if (coupon.getUseTimeType() == 2) {
            useEnd = DateUtils.dateToString(DateUtils.getDateAfterHour(coupon.getUseTimeHour()), DateUtils.TIMESTAMP);
        }
        if (coupon.getUseTimeType() == 3) {
            useEnd = DateUtils.dateToString(DateUtils.getEndOfDay(date), DateUtils.TIMESTAMP);
        }
        Order order = new Order();
        order.setId(UUIDGenerator.getUUID());
        order.setOrderNum(UUIDGenerator.getOrderIdByTime());
        order.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        order.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        order.setCouponId(request.getCouponId());
        order.setUserId(request.getUserId());
        order.setCount(request.getCount());
        order.setStatusShow(0);
        order.setStatusRemove(0);
        order.setStoreId(request.getStoreId());
        //如果是积分支付
        if (coupon.getValueType() == 1) {
            if (request.getUserIntegral() < (coupon.getIntegral() * request.getCount())) {
                orderDTO.setMsg("用户积分不足");
                return orderDTO;
            }
            //如果券是不限量的券，直接给用户创建一张被购买的券
            if (coupon.getSumType() == 1) {
                for (int i = 0; i < request.getCount(); i++) {
                    CouponCode couponCode = new CouponCode();
                    couponCode.setId(UUIDGenerator.getUUID());
                    couponCode.setCouponCode(UUIDGenerator.getOrderIdByTime());
                    couponCode.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    couponCode.setAddTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    couponCode.setCouponId(coupon.getId());
                    couponCode.setUserId(request.getUserId());
                    couponCode.setStatus(0);
                    couponCode.setType(coupon.getType());
                    couponCode.setUseTimeEnd(useEnd);
                    couponCode.setCouponName(coupon.getName());
                    couponCode.setUseTimeStart(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    couponCode.setSenderName(senderName);
                    couponCodeRepository.saveAndFlush(couponCode);
                }
            } else {
                if (coupon.getRemainTotal() >= request.getCount()) {
                    couponRepository.updateRemainTotal(request.getCouponId(), request.getCount());
                    //根据优惠券使用期限和券id查找对应的code，并将code锁定
                    List<CouponCode> couponCodeList = couponCodeRepository.queryByCouponIdAndStatus(coupon.getId());
                    if (couponCodeList.size() > 0) {
                        for (int i = 0; i < request.getCount(); i++) {
                            CouponCode couponCode = couponCodeList.get(i);
                            if (coupon.getUseTimeType() == 1) {
                                couponCodeRepository.addUserCouponCode1(couponCode.getId(),request.getUserId(), DateUtils.dateToString(date, DateUtils.TIMESTAMP), senderName, useEnd,coupon.getUseTimeStart());
                            } else {
                                couponCodeRepository.addUserCouponCode1(couponCode.getId(), request.getUserId(), DateUtils.dateToString(date, DateUtils.TIMESTAMP), senderName, useEnd, DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                            }
                        }
                    }
                } else {
                    orderDTO.setMsg("商品数量不足");
                    return orderDTO;
                }
            }
            //支付积分
            order.setIntegral(coupon.getIntegral() * request.getCount());
            order.setPrice(0.0);
            //设置订单状态为已支付
            order.setStatus(1);
            orderRepository.saveAndFlush(order);
            //订单放入队列接受处理
            solveOrder(order, coupon, request.getStoreId());
        } else {
            if (coupon.getValueType() == 2) {
                if (request.getUserIntegral() < (coupon.getIntegral() * request.getCount())) {
                    orderDTO.setMsg("用户积分不足");
                    return orderDTO;
                }
            }
            //如果券是不限量的券，直接给用户创建一张被购买的券
            if (coupon.getSumType() == 1) {
                for (int i = 0; i < request.getCount(); i++) {
                    CouponCode couponCode = new CouponCode();
                    couponCode.setId(UUIDGenerator.getUUID());
                    couponCode.setCouponCode(UUIDGenerator.getOrderIdByTime());
                    couponCode.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    couponCode.setAddTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    couponCode.setCouponId(coupon.getId());
                    couponCode.setUserId(request.getUserId());
                    couponCode.setStatus(-1);
                    couponCode.setType(coupon.getType());
                    couponCode.setUseTimeEnd(useEnd);
                    couponCode.setCouponName(coupon.getName());
                    couponCode.setUseTimeStart(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                    couponCode.setSenderName(senderName);
                    couponCodeRepository.saveAndFlush(couponCode);
                }
            } else {
                if (coupon.getRemainTotal() >= request.getCount()) {
                    couponRepository.updateRemainTotal(request.getCouponId(), request.getCount());
                    //根据优惠券使用期限和券id查找对应的code，并将code锁定
                    List<CouponCode> couponCodeList = couponCodeRepository.queryByCouponIdAndStatus(coupon.getId());
                    if (couponCodeList.size() > 0) {
                        for (int i = 0; i < request.getCount(); i++) {
                            CouponCode couponCode = couponCodeList.get(i);
                            if (coupon.getUseTimeType() == 1) {
                                couponCodeRepository.addUserCouponCodeAndStatus1(couponCode.getId(),request.getUserId(), DateUtils.dateToString(date, DateUtils.TIMESTAMP), senderName, useEnd,coupon.getUseTimeStart());
                            } else {
                                couponCodeRepository.addUserCouponCodeAndStatus1(couponCode.getId(), request.getUserId(), DateUtils.dateToString(date, DateUtils.TIMESTAMP), senderName, useEnd, DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                            }
                        }
                    }
                } else {
                    orderDTO.setMsg("商品数量不足");
                    return orderDTO;
                }
            }
            if (coupon.getValueType() == 2) {
                //支付积分
                order.setIntegral(coupon.getIntegral() * request.getCount());
            }
            //如果是金额支付
            order.setPrice(Double.parseDouble(coupon.getPrice()) * request.getCount());
            //设置订单状态为未支付
            order.setStatus(0);
            orderRepository.saveAndFlush(order);
        }
        BeanUtils.copyProperties(order, orderDTO);
        String type = coupon.getType().toString();
        orderDTO.setType(type);
        return orderDTO;
    }


    /**
     * 生成订单
     *
     * @param request
     * @return
     */
    public OrderDTO saveOrder2(OrderRequest request) {
        OrderDTO orderDTO = new OrderDTO();
        // 查询用户订单是否已存在，存在即吊起支付
        Order oldOrder = orderRepository.queryByUserIdAndCouponId(request.getUserId(), request.getCouponId());
        if (oldOrder != null) {
            String s1 = orderCacheDao.get(oldOrder.getOrderNum());
            if (s1 != null) {
                BeanUtils.copyProperties(oldOrder, orderDTO);
                return orderDTO;
            }
        }
        Integer integral;
        UserRequestBody userRequestBody = new UserRequestBody();
        //通过openid查找用户
        userRequestBody.setUserId(request.getUserId());
        String postJson1 = Request.postJson(userUrl + "/user/qurey_by_user_id", userRequestBody);
        JSONObject jsonObject1 = JSON.parseObject(postJson1);
        if (null == jsonObject1) {
            orderDTO.setMsg("系统异常");
            return orderDTO;
        }
        Integer resCode1 = jsonObject1.getInteger("resCode");
        UserDTO data1;
        if (0 == resCode1) {
            data1 = jsonObject1.getJSONObject("data").toJavaObject(UserDTO.class);
            integral = data1.getIntegral();
        } else {
            orderDTO.setMsg("未查询到该用户");
            return orderDTO;
        }
        Date date = new Date();
        Coupon coupon = couponRepository.findByCouponId(request.getCouponId());
        if (coupon == null) {
            orderDTO.setMsg("没有对应商品");
            return orderDTO;
        }
        if (date.before(DateUtils.stringToDate(coupon.getBuyTimeStart(), DateUtils.TIMESTAMP)) || date.after(DateUtils.stringToDate(coupon.getBuyTimeEnd(), DateUtils.TIMESTAMP))) {
            orderDTO.setMsg("未到购买时间");
            return orderDTO;
        }
        Square square = squareRepository.findByStatus();
        //判断用户是否超出商城限制购买的笔数  TODO
        if (square.getCount() != null && square.getCount() > 0) {
            List<Order> orderList = orderRepository.queryByUserIdPerDay(request.getUserId(), DateUtils.dateToString(date, DateUtils.DATE));
            if (orderList.size() >= square.getCount()) {
                orderDTO.setMsg("超出商城当天兑换数量限制");
                return orderDTO;
            }
        }
        //判断用户当天购买的该券数量是否超出限制  TODO
        if (coupon.getCount() != null && coupon.getCount() > 0) {
            List<CouponCode> userCoupon = couponCodeRepository.queryByUserIdAndCouponId(request.getUserId(), request.getCouponId(), DateUtils.dateToString(date, DateUtils.DATE));
            if (request.getCount() > coupon.getCount() || request.getCount() + userCoupon.size() > coupon.getCount()) {
                orderDTO.setMsg("超出卡券当天兑换数量限制");
                return orderDTO;
            }
        }
        //判断用户在优惠券可购买期间购买的该券数量是否超出限制  TODO
        if (coupon.getBuyTimeCount() != null && coupon.getBuyTimeCount() > 0) {
            List<CouponCode> buyCoupons = couponCodeRepository.queryByUserIdAndCouponId(request.getUserId(), request.getCouponId());
            if (request.getCount() > coupon.getBuyTimeCount() || request.getCount() + buyCoupons.size() > coupon.getBuyTimeCount()) {
                orderDTO.setMsg("超出有效期内兑换数量限制");
                return orderDTO;
            }
        }
        Order order = new Order();
        order.setId(UUIDGenerator.getUUID());
        order.setOrderNum(DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.getRandomStr());
        order.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        order.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        order.setCouponId(request.getCouponId());
        order.setUserId(request.getUserId());
        order.setCount(request.getCount());
        order.setStatusShow(0);
        order.setStatusRemove(0);
        order.setStoreId(request.getStoreId());
        //如果是积分支付
        if (coupon.getValueType() == 1) {
            if (integral == null || (integral < (coupon.getIntegral() * request.getCount()))) {
                orderDTO.setMsg("用户积分不足");
                return orderDTO;
            }
            if (coupon.getSumType() == 0) {
                Integer couponRemainTotal;
                String s = couponCacheDao.get(coupon.getId());
                if (s == null) {
                    String save = couponCacheDao.save(coupon.getId(), coupon.getRemainTotal().toString());
                    couponRemainTotal = Integer.valueOf(save);
                } else {
                    couponRemainTotal = Integer.valueOf(s);
                }
                if (couponRemainTotal >= request.getCount()) {
                    Integer count = couponRemainTotal - request.getCount();
                    couponCacheDao.save(coupon.getId(), count.toString());
                    // 将订单置入缓存
                    orderCacheDao.save(order.getOrderNum());
                } else {
                    orderDTO.setMsg("商品数量不足");
                    return orderDTO;
                }
            }
            //支付积分
            order.setIntegral(coupon.getIntegral() * request.getCount());
            order.setPrice(0.0);
            order.setStatus(0);
            order = orderRepository.saveAndFlush(order);
            if (order != null) {
                boolean b = updateOrder(order.getOrderNum(), null);
                if (b) {
                    //设置订单状态为已支付
                    order.setStatus(1);
                } else {
                    //设置订单状态为未支付
                    order.setStatus(0);
                }
            }
//            solveOrder(order, coupon, request.getStoreId());
            orderRepository.saveAndFlush(order);
        } else {
            if (coupon.getValueType() == 2) {
                if (integral == null || (integral < (coupon.getIntegral() * request.getCount()))) {
                    orderDTO.setMsg("用户积分不足");
                    return orderDTO;
                }
            }
            //如果券是不限量的券，直接给用户创建一张被购买的券
            if (coupon.getSumType() == 0) {
                Integer couponRemainTotal;
                String s = couponCacheDao.get(coupon.getId());
                if (s == null) {
                    String save = couponCacheDao.save(coupon.getId(), coupon.getRemainTotal().toString());
                    couponRemainTotal = Integer.valueOf(save);
                } else {
                    couponRemainTotal = Integer.valueOf(s);
                }
                if (couponRemainTotal >= request.getCount()) {
                    Integer count = couponRemainTotal - request.getCount();
                    couponCacheDao.save(coupon.getId(), count.toString());
                    // 将订单置入缓存
                    orderCacheDao.save(order.getOrderNum());
                } else {
                    orderDTO.setMsg("商品数量不足");
                    return orderDTO;
                }
            }
            if (coupon.getValueType() == 2) {
                //支付积分
                order.setIntegral(coupon.getIntegral() * request.getCount());
            }
            //如果是金额支付
            order.setPrice(Double.parseDouble(coupon.getPrice()) * request.getCount());
            //设置订单状态为未支付
            order.setStatus(0);
            orderRepository.saveAndFlush(order);
        }
        BeanUtils.copyProperties(order, orderDTO);
        String type = coupon.getType().toString();
        orderDTO.setType(type);
        return orderDTO;
    }


    /**
     * 订单处理
     */
    private void solveOrder(Order order, Coupon coupon, String storeId) {
        IntegralOutPut integralOutPut = new IntegralOutPut();
        if (coupon.getType() == 3) {
            integralOutPut.setConsumeType("parking");
            integralOutPut.setForeignKeyId("");
        } else {
            integralOutPut.setConsumeType("store");
            integralOutPut.setForeignKeyId("");
        }
        //}
        integralOutPut.setIntegralPoint(order.getIntegral().toString());
        if (order.getPrice() != null) {
            integralOutPut.setMoney(order.getPrice().toString());
        }
        integralOutPut.setOrderNum(order.getOrderNum());
        integralOutPut.setUserId(order.getUserId());
        integralOutPut.setSource("商城积分兑换");
        integralOutPut.setTradeAction(1);
        integralOutPut.setTradingContent("商城积分兑换：" + coupon.getName());
        //通过mq消息队列发送给资源模块关系
//        amqpTemplate.convertAndSend("integral.exchange", "integral.store", JsonUtil.toJson(integralOutPut));

        //将计算结果放到MQ队列去补充明细的余额

        String exchange = "integral.exchange";
        String routingKey = "integral.store";
        rabbitSender.sendMessageToMQ(integralOutPut, null, exchange, routingKey);
    }

    /**
     * 查看订单
     *
     * @param request
     * @return
     */
    public List<Object> queryListByUserId(OrderRequest request) {
        List<Object> objectList = new LinkedList<>();
        Integer page = request.getPage() == null ? 0 : request.getPage();
        Integer size = request.getSize() == null ? 100 : request.getSize();
        List<Order> orderList = orderRepository.queryByUserId(request.getUserId(), page * size, size);
        for (Order order : orderList) {
            Map<String, Object> map = new HashMap<>();
            Coupon coupon = couponRepository.findByCouponId(order.getCouponId());
            if (coupon == null) {
                continue;
            }
            IdDTO idDTO = new IdDTO();
            idDTO.setForeignKeyId(order.getCouponId());
            ImageDTO imageDTO = restTemplate.postForObject("http://quanquan-resource/image/image_query", idDTO, ImageDTO.class);
            String image = null;
            if (imageDTO.getImageDTOs().size() > 0) {
                image = imageDTO.getImageDTOs().get(0).getImageAddress();
            } else {
                image = "";
            }
            map.put("couponName", coupon.getName());
            map.put("integral", coupon.getIntegral());
            map.put("valueType", coupon.getValueType());
            map.put("price", coupon.getPrice());
            map.put("createTime", order.getCreateTime());
            map.put("count", order.getCount());
            map.put("image", image);
            objectList.add(map);
        }
        return objectList;
    }

    public boolean updateOrder(String orderNum, String transactionId) {
        Order order = orderRepository.findByOrderNum(orderNum);
        if (order == null) {
            return false;
        }
        //先扣除积分
        Coupon coupon = couponRepository.findByCouponId(order.getCouponId());
        if (coupon != null) {
            if (coupon.getValueType() == 1 || coupon.getValueType() == 2) {
                // 处理积分扣减
                solveOrder(order, coupon, "");
                // 纯积分支付
                if (coupon.getValueType() == 1) {
                    boolean b = orderCacheDao.delete(order.getOrderNum());
                    if (b) {
                        order.setStatus(1);
                        order.setUpdateTime(DateUtils.currentDate());
                        orderRepository.saveAndFlush(order);
                    }
                } else {
                    // 积分+现金支付
                    order.setStatus(1);
                    order.setUpdateTime(DateUtils.currentDate());
                    order.setTransactionId(transactionId);
                    orderRepository.saveAndFlush(order);
                }
            } else {
                // 现金支付
                order.setStatus(1);
                order.setUpdateTime(DateUtils.currentDate());
                order.setTransactionId(transactionId);
                orderRepository.saveAndFlush(order);
            }
            // 发券
            CouponRequest couponRequest = new CouponRequest();
            couponRequest.setId(coupon.getId());
            couponRequest.setUserId(order.getUserId());
            couponRequest.setCount(order.getCount());
            String s = couponService.sendCoupon(couponRequest);
            if ("发券成功".equals(s)) {
                return true;
            } else {
                return false;
            }
        }
        //将支付成功的券更新给用户
        /*List<CouponCode> couponCodeList = couponCodeRepository.queryByCouponIdAndUserIdAndStatus(order.getCouponId(), order.getUserId());
        for (int i = 0; i < order.getCount(); i++) {
            CouponCode couponCode = couponCodeList.get(i);
            couponCode.setStatus(0);
            couponCodeRepository.saveAndFlush(couponCode);
        }*/
        return false;
    }
    public Order findByOrderNum(String orderNum) {
        return orderRepository.findByOrderNum(orderNum);
    }

    /**
     * 年度消费总积分
     *
     * @param request
     * @return
     */
    public Map<String, Object> queryByUserIdYear(OrderRequest request) {
        Integer sumIntegral = queryIntegralByUserIdYear(request.getUserId());
        Double sumPrice = queryPriceByUserIdYear(request.getUserId());
        Map<String, Object> map = new HashMap<>();
        map.put("sumIntegral", sumIntegral);
        map.put("sumPrice", sumPrice);
        return map;
    }

    public Integer queryIntegralByUserIdYear(String userId) {
        Integer query = orderRepository.queryIntegralByUserIdYear(userId);
        if (query == null) {
            return 0;
        } else {
            return query;
        }
    }

    public Double queryPriceByUserIdYear(String userId) {
        Double query = orderRepository.queryPriceByUserIdYear(userId);
        if (query == null) {
            return 0.0;
        } else {
            return query;
        }
    }

    /**
     * 后台用订单记录
     *
     * @return
     */
    public List<AllOrderDTO> findByManagement(OrderRequest requestBody) {
        Integer page = requestBody.getPage() == null ? 0 : requestBody.getPage();
        Integer size = requestBody.getSize() == null ? 100 : requestBody.getSize();
        List<AllOrderDTO> allOrderDTOS = new LinkedList<>();
        List<Object[]> objects = orderRepository.queryByCount(page * size, size);
        for (Object[] obj : objects) {
            AllOrderDTO allOrderDTO = new AllOrderDTO();
            allOrderDTO.setCouponName(obj[0].toString());
            if (obj[1] != null) {
                allOrderDTO.setCount(Integer.parseInt(obj[1].toString()));
            } else {
                allOrderDTO.setCount(0);
            }
            if (obj[2] != null) {
                allOrderDTO.setIntegral(Integer.parseInt(obj[2].toString()));
            } else {
                allOrderDTO.setIntegral(0);
            }
            if (obj[3] != null) {
                System.out.println(obj[3]);
                allOrderDTO.setPrice(Double.parseDouble(obj[3].toString()));
            } else {
                allOrderDTO.setPrice(0.0);
            }
            if (obj[3] != null) {
                System.out.println(obj[3]);
                allOrderDTO.setPrice(Double.parseDouble(obj[3].toString()));
            } else {
                allOrderDTO.setPrice(0.0);
            }
            if (obj[4] != null){
                allOrderDTO.setCouponId(obj[4].toString());
            }else{
                allOrderDTO.setCouponId("");
            }

            allOrderDTOS.add(allOrderDTO);
        }
        return allOrderDTOS;
    }

    /**
     * 后台用订单记录
     *
     * @return
     */
    public List<AllOrderDTO> findByCouponId(String couponId) {
        List<AllOrderDTO> allOrderDTOS = new LinkedList<>();
        List<Object[]> objects = orderRepository.queryByCouponId(couponId);
        for (Object[] obj : objects) {
            AllOrderDTO allOrderDTO = new AllOrderDTO();
            if (obj[0] != null) {
                allOrderDTO.setCreateTime(obj[0].toString());
            }
            if (obj[1] != null) {
                allOrderDTO.setOrderNum(obj[1].toString());
            }
            if (obj[2] != null) {
                allOrderDTO.setUserName(obj[2].toString());
            }
            allOrderDTOS.add(allOrderDTO);
        }
        return allOrderDTOS;
    }

    public Integer queryBySumCount() {
        return orderRepository.queryBySumCount().size();
    }

}
